package impl

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/infraboard/mcube/exception"
	"github.com/infraboard/mcube/sqlbuilder"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"kubernetes-manage/apps/cluster"
	"kubernetes-manage/k8s"
)

func (s *service) CreateCluster(ctx context.Context, req *cluster.CreateClusterRequest) (*cluster.ClusterInfo, error) {

	// 参数校验
	if err := req.Validate(); err != nil {
		return nil, err
	}
	// 创建客户端
	client, err := k8s.NewClient(req.KubeConfig)
	if err != nil {
		return nil, fmt.Errorf("连接客户端失败,检查kubeconfig文件: %s", err)
	}

	// kube_config base64内容加密
	encodingstr := base64.StdEncoding.EncodeToString([]byte(req.KubeConfig))

	ins, err := cluster.NewClusterInfo(req)
	if err != nil {
		return nil, err
	}
	ins.ClusterVersion = client.ServerVersion()
	ins.ClusterName = req.ClusterName
	ins.KubeConfig = encodingstr

	node, err := client.List().ListNode(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("get node error: %s", err)
	}

	// 获取节点名称，节点ip，节点状态
	for _, v := range node.Items {
		ins.Node.NodeIp = v.Status.Addresses[0].Address
		ins.Node.NodeName = v.Name
		for _, j := range v.Status.Conditions {
			if j.Status == "True" {
				ins.Node.NodeStatus = "Ready"
			} else {
				ins.Node.NodeStatus = "NotReady"
			}
		}
	}

	// 保存数据到mysql中
	if err := s.insert(ctx, ins); err != nil {
		return nil, fmt.Errorf("inster cluster info error: %s", err)
	}
	//return ins, nil
	s.log.Debugf("cluster info: %s", ins)
	return ins, nil
}

func (s *service) QueryCluster(ctx context.Context, req *cluster.CreateClusterRequest) (*cluster.ClusterSet, error) {

	set := cluster.NewCluseterSet()

	query := sqlbuilder.NewQuery(querySecretSQL)

	querySQL, args := query.BuildQuery()
	queryStmt, err := s.db.Prepare(querySQL)
	if err != nil {
		return nil, err
	}
	defer queryStmt.Close()

	rows, err := queryStmt.Query(args...)
	if err != nil {
		return nil, exception.NewInternalServerError(err.Error())
	}
	ins := cluster.NewDefaultInfo()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		err := rows.Scan(&ins.Id, &ins.CreateAt, &ins.ClusterVersion, &ins.ClusterName, &ins.KubeConfig, &ins.Node.NodeName, &ins.Node.NodeIp, &ins.Node.NodeStatus)
		if err != nil {
			return nil, exception.NewInternalServerError("query cluster info error, %s", err.Error())
		}

	}

	return set, nil
}
